'use strict';
/** 
 * controller for User Profile Example
 */
app.controller('adminUserListCtrl', ["$rootScope", "$scope", "$state", "$timeout", "$interval", "$modal", "SweetAlert", "i18nService", "uiGridConstants", "uiGridGroupingConstants", "Restangular", "api_user_data", "api_login", function($rootScope, $scope, $state, $timeout, $interval, $modal, SweetAlert, i18nService, uiGridConstants, uiGridGroupingConstants, Restangular, api_user_data, api_login) {
    $scope.langs = i18nService.getAllLangs();
    $scope.lang = 'zh-cn';

    i18nService.setCurrentLang($scope.lang);

    var loginUser = $rootScope.user;

    //$scope.allright=false;
    //$scope.allrightnot=true;
    $scope.gridOptions = {};
    $scope.gridOptions.data = 'myData';
    $scope.gridOptions.enableColumnResizing = true;
    $scope.gridOptions.enableFiltering = true;
    $scope.gridOptions.enableGridMenu = false;
    $scope.gridOptions.enableRowSelection = true;
    $scope.gridOptions.showGridFooter = true;
    $scope.gridOptions.showColumnFooter = false;
    $scope.gridOptions.fastWatch = true;
    $scope.gridOptions.useExternalFiltering = true;
    $scope.gridOptions.useExternalPagination = true;
    $scope.gridOptions.paginationPageSizes = [10];
    $scope.gridOptions.paginationPageSize = 10;
    $scope.gridOptions.multiSelect = true;

    //$scope.gridOptions.rowTemplate= "<div ng-dblclick=\"grid.appScope.onDblClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" ui-grid-one-bind-id-grid=\"rowRenderIndex + '-' + col.uid + '-cell'\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" role=\"{{col.isRowHeader ? 'rowheader' : 'gridcell'}}\" ui-grid-cell></div>";

    $scope.gridOptions.rowIdentity = function(row) {
        return row.id;
    };
    $scope.gridOptions.getRowIdentity = function(row) {
        return row.id;
    };


    $scope.transferRole = function(roles) {
        var tempValue = "";
        angular.forEach(roles, function(item) {
            if (tempValue != "") {
                tempValue = tempValue + "/";
            }
            tempValue = tempValue + item.role;
        })
        return tempValue;
    }

    $scope.transferStatus = function(flag) {
        return (flag == 0) ? "有效" : "无效";
    }

    //remote data

    $scope.gridOptions.columnDefs = [{
            name: '编辑',
            cellTemplate: '<a class="btn btn-sm btn-info" ng-click="grid.appScope.saveData(row.entity)" tooltip="编辑">' +
                '<i class="fa fa-pencil-square-o"/></a>' +
                '<a class="btn btn-sm btn-info" ng-click="grid.appScope.resetpassword(row.entity.id)" tooltip="重置密码">' +
                '<i class="ti-back-right"/></a>',
            width: 100,
            enableFiltering: false
        },
        { name: 'name', displayName: '姓名', width: 100 },
        { name: 'account', displayName: '工号', width: 80 },
        {
            name: 'gender',
            displayName: '性别',
            editableCellTemplate: 'ui-grid/dropdownEditor',
            width: 80,
            editDropdownValueLabel: 'gender',
            editDropdownOptionsArray: [
                { id: '男', gender: '男' },
                { id: '女', gender: '女' }
            ],
            enableFiltering: false
        },
        { name: 'dept.dept', displayName: '部门', width: 140, enableFiltering: false },
        // { name:'email', displayName:'邮箱', width:100,enableFiltering:false},
        { name: 'phone', displayName: '电话', width: 100, enableFiltering: false },
        { name: 'nickname', displayName: '昵称', width: 100, enableFiltering: false },
        { name: 'flag', displayName: '状态', cellTemplate: '<div class="ui-grid-cell-contents">{{grid.appScope.transferStatus(row.entity.flag)}}</div>', width: 100, enableFiltering: false },
        { name: 'role', cellTemplate: '<div class="ui-grid-cell-contents">{{grid.appScope.transferRole(row.entity.role)}}</div>', displayName: '角色', width: 140, enableFiltering: false }
        //'<div class="links cl-effect-1">' +
        //      '<a ng-click="grid.appScope.selectRowFunction(row.entity)" tooltip="编辑" tooltip-placement="left"><i class="fa fa-pencil-square-o"></i></a>'+
        //      '</div>' , width:100, enableFiltering:false}
    ];


    $scope.refresh = function(style, filterData) {
        var filtersData = {
            "assignee": $rootScope.user.id,
            "candidateGroups": $rootScope.user.group[0].id,
            idx: 0,
            sum: 10
        };
        $scope.gridOptions.refresh();
        $scope.refreshData('expand-right', filtersData);
    };

    $scope.resetpassword = function(id) {
        var modalInstance = $modal.open({
            templateUrl: 'assets/views/system/getright.html',
            controller: function($scope, $modalInstance) {
                var data
                $scope.ok = function() {
                    $modalInstance.dismiss('cancel');
                    api_login.resetpwd(id).then(function(response) {
                        var myData = Restangular.stripRestangular(response);
                        console.log("myData=" + JSON.stringify(myData));
                        if (response.status == 200) {
                            SweetAlert.swal({
                                title: "重置成功!",
                                type: "success",
                                confirmButtonColor: "#007AFF"
                            });
                        } else {
                            SweetAlert.swal({
                                title: "操作异常!",
                                text: "系统异常，请稍后重试，或者联系管理员！",
                                type: "error"
                            });
                        }
                    })

                };

                $scope.cancel = function() {
                    $modalInstance.dismiss('cancel');
                };
            }
        })
    }

    $scope.saveData = function(data) {
        var modelData = {
            model: {
                user: data
            }
        };
        console.log("modelData=" + JSON.stringify(modelData));
        $state.go('app.system.form', { formKey: 'system_edit', service: 'api_user_data', model: JSON.stringify(modelData) });
    };
    $scope.addData = function() {
        var modelData = {
            model: {
                user: {
                    role: [{ id: 2, rolecode: "user", role: "总行员工", flag: 1, roletype: 0 }],
                    flag: 0
                }
            }
        };
        console.log("modelData=" + JSON.stringify(modelData));
        $state.go('app.system.form', { formKey: 'system_edit', service: 'api_user_data', model: JSON.stringify(modelData) });
    }

    $scope.removeData = function() {
        var rmvList = [];
        angular.forEach($scope.selected.items, function(item) {
            rmvList.push(item.id);
        });
        if (rmvList.length > 0) {
            api_user_data.rmvData('user', rmvList).then(function(response) {
                if (response.data) {
                    SweetAlert.swal({
                        title: "删除成功!",
                        type: "success",
                        confirmButtonColor: "#007AFF"
                    }, function() {
                        $scope.myData = _.reject($scope.myData, function(o) { return _.includes(rmvList, o.id); });
                        $scope.selected = {
                            items: []
                        };
                    });

                } else {
                    SweetAlert.swal({
                        title: "操作异常!",
                        text: "系统异常，请稍后重试，或者联系管理员！",
                        type: "error"
                    });
                }
            })
        }
    }


    $scope.selected = {
        items: []
    }

    $scope.editted = {
        items: []
    }

    $scope.gridOptions.onRegisterApi = function(gridApi) {
        $scope.gridApi = gridApi;

        gridApi.edit.on.afterCellEdit($scope, function(rowEntity, colDef, newValue, oldValue) {
            // console.log(rowEntity);
        });


        gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
            var filtersData = $scope.memoryfilterData;
            filtersData.idx = newPage - 1;
            filtersData.sum = pageSize;
            $rootScope['idx'] = newPage;
            $scope.refreshData('expand-right', filtersData);
        });

        gridApi.selection.on.rowSelectionChanged($scope, function(scope) {
            var j = 0;
            for (var i = 0; i <= scope.grid.appScope.selected.items.length; i++) {
                if (scope.grid.appScope.selected.items[i] == scope.entity) {
                    j++;
                    break;
                }
            }
            // console.log("j="+j)
            if (j == 1) {
                scope.grid.appScope.selected.items.splice(i, 1);
            } else {
                scope.grid.appScope.selected.items.push(scope.entity)
            }
        });

        gridApi.core.on.filterChanged($scope, function() {
            var grid = this.grid;
            var filtersData = {
                idx: 0,
                sum: 10
            };
            angular.forEach(grid.columns, function(item) {
                if (item.enableFiltering) {
                    if (angular.isDefined(item.filters[0].term) && item.filters[0].term != '') {
                        if (angular.isUndefined(filtersData['user'])) {
                            filtersData['user'] = {};
                        }
                        filtersData['user']['flag'] = -1;
                        filtersData['user'][item.field] = item.filters[0].term;
                    }
                }
            });
            $scope.memoryfilterData = filtersData;
            $scope.refreshData('expand-right', filtersData);
        });
    };


    var defaultFilterData = {
        "idx": 0,
        "sum": 10
    };

    $scope.memoryfilterData = {
        "idx": 0,
        "sum": 10
    }
    if ($rootScope['cmdbs'] != 'user') { $rootScope.idx = 1 }
    if (angular.isDefined($rootScope.idx) && $rootScope.cmdbs != "false") {
        $rootScope.cmdbs = 'user';
        defaultFilterData.idx = $rootScope.idx - 1;
    }
    $scope.ldloading = {};

    $scope.refreshData = function(style, filterData) {
        $scope.ldloading[style.replace('-', '_')] = true;
        if (angular.isUndefined(filterData)) {
            defaultFilterData.idx = $rootScope.idx - 1;
            filterData = defaultFilterData;
        }
        if (angular.isDefined($scope.searchTypes)) {
            filterData['searchType'] = $scope.searchTypes;
        }
        $scope.myData = [];
        filterData['flag'] = -1;
        console.log("filterData=" + JSON.stringify(filterData))
        api_user_data.fetchDataList('user', filterData).then(function(data) {
            var myData = Restangular.stripRestangular(data);
            $scope.gridOptions.totalItems = myData.totalNum;
            $scope.myData = myData.list;
            $scope.ldloading[style.replace('-', '_')] = false;
            // console.log("$scope.myData="+JSON.stringify($scope.myData))
        }, function() {
            $scope.ldloading[style.replace('-', '_')] = false;
        });

    };

    $scope.refreshData('expand-right', defaultFilterData);
}]);